# -*- coding=utf-8 -*-
# @Time    : 2021/3/10 10:48
# @Author  : lhys
# @FileName: major_tools.py

import sqlite3
import requests
import lxml.etree as le

headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0'
}
proxies = {
    'http:' : ''
}
major_url = 'https://www.dytt.com'

def create_cache(conn, table, values, filed):
    filed_s = ', '.join(filed) if type(filed) == list else filed
    v_s = ','.join(['?' for i in range(len(filed))])
    sql = f'insert into {table}({filed_s}) values ({v_s})'
    for data in values:
        value = tuple([data[key] if key in data else '' for key in filed] if type(data) == dict else data)
        conn.execute(sql, value)
    conn.commit()

def select_data(conn, table_name):
    cu = conn.cursor()
    sql = f'select * from {table_name}'
    return cu.execute(sql).fetchall()

def choose_video(kw, conn):
    result = select_data(conn, 'choose')
    if result:
        return result
    url = f'https://www.dytt.com/vodsearch/-------------.html?wd={kw}'
    response = requests.get(url=url, headers=headers).text
    search_list = []
    print('{:2s}: {:^30s} {:^50s} {:^10s}'.format('序号', '搜索结果名称', '搜索结果类型', '上映时间'))
    for i, uc in enumerate(le.HTML(response).xpath('//tr')[1:]):
        name = uc.xpath('./td[1]/a/text()')[0]
        url = major_url + uc.xpath('./td[1]/a/@href')[0]
        type = uc.xpath('./td[2]/text()')[0] if len(uc.xpath('./td[2]/text()')) != 0 else ''
        r_time = uc.xpath('./td[5]/text()')[0]
        search_list.append(
            {
                'kw' : kw,
                'name' : name,
                'url' : url
            }
        )
        print('{:>2d}: {:^30s} {:^50s} {:^10s}'.format(i + 1, name, type, r_time))
    choose_video_data = [search_list[eval(char) - 1] for char in input('请选择要下载的视频序号(可多选，用空格分离)：').split(' ') if eval(char) <= len(search_list)]
    create_cache(conn, 'choose', choose_video_data, ['kw', 'name', 'url'])
    return choose_video_data

def get_content_ul(kw, conn):
    '''
        本函数用来获得每个视频的播放页
        :param url: 视频的简介页的链接
        :return: 每个视频播放页的的链接
        '''

    name = url_dict['name']
    i_url = url_dict['url']
    result = {name: []}
    req = requests.get(i_url, headers=headers).text
    video_list = le.HTML(req).xpath('//ul/a')
    for video in video_list[1:]:
        url = major_url + video.xpath('./@href')[0]
        v_name = video.xpath('./text()')[0]
        result[name].append(
            {
                'name': name + v_name,
                'url': url
            }
        )
    return result